package com.cjx.usercenter.contorller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.cjx.usercenter.common.Constants;
import com.cjx.usercenter.pojo.domain.User;
import com.cjx.usercenter.pojo.request.LoginUser;
import com.cjx.usercenter.pojo.request.RegisterRequest;
import com.cjx.usercenter.pojo.vo.UserVo;
import com.cjx.usercenter.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.cjx.usercenter.common.Constants.USER_RECORD_STATUS;

/**
 * @Description 用户的Controller
 * @Author cjx
 * @Date 2023/12/11 18:26
 **/
@RestController()
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     * @param registerRequest 登录参数请求体
     * @return
     */
    @PostMapping("/register")
    public int register(@RequestBody RegisterRequest registerRequest){
        if (registerRequest == null){
            return -1;
        }
        int i = userService.userRegister(registerRequest);
        return i;
    }

    /**
     * 用户登录
     * @param loginUser 登录参数
     * @param request request
     * @return 脱敏的用户数据
     */
    @PostMapping("/login")
    public UserVo loginUser(@RequestBody LoginUser loginUser , HttpServletRequest request){
        if (loginUser == null){
            return null;
        }
        String account = loginUser.getAccount();
        String password = loginUser.getPassword();
        if (StrUtil.isAllBlank(account,password)){
            return null;
        }
        UserVo userVo = userService.loginUser(account, password, request);
        System.out.println(userVo);
        return userVo;
    }

    /**
     * 返回当前用户
     * @param request request
     * @return 用户数据
     */
    @GetMapping("/current")
    public UserVo getCurrentUser(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute(USER_RECORD_STATUS);
        if (user == null){
            return null;
        }
        Integer uid = user.getUid();
        User userById = userService.getById(uid);
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(userById,userVo);
        return userVo;
    }

}
